package com.ericsson.eritask.dao.impl;

import java.io.IOException;
import java.io.InputStream;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ericsson.eritask.dao.CommentDAO;
import com.ericsson.eritask.domain.Comment;
import com.ericsson.eritask.domain.CommentDocument;
import com.ericsson.eritask.dto.CommentsDTO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSFile;

@Repository
public class CommentDaoImpl implements CommentDAO{

	
	@Autowired
	MongoOperations  mongoOperation;
	
	@Autowired
	GridFsOperations gridOperations;
	
	@Autowired
	MongoTemplate mongoTemplate;
	
	@PersistenceContext
	EntityManager em;
	
	
	@Transactional
	@Override
	public void insertComment(Comment comment) {

		em.persist(comment);

	}

	@Override
	public String insertCommentFile(InputStream file, String fileName) {

		  DBObject metaData = new BasicDBObject(); 
		  metaData.put("extra1", "anything 1"); 
		  metaData.put("extra2", "anything 2");
	
		GridFSFile storedFile = null;
		try {
		System.out.println("filename in insertCommentFile()::::" +fileName);
			storedFile = gridOperations.store(file,fileName, metaData);
			String id = storedFile.getId().toString();
			System.out.println("File id in CommentDaoImpl is" + id);
		} finally {
			if (file != null) {
				try {
					file.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return storedFile.getId().toString();
		
	}

	@Override
	public String insertDocument(CommentDocument doc) {

		// mongoOperation.insert(doc);
		mongoTemplate.insert(doc);
		// mongoOperation.get
		System.out.println("doc.getDocId():::::::"+doc.getDocId());
		return doc.getDocId();
	}

}
